package com.xjprojectc.business.action;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.xjprojectc.base.action.SysBaseAction;
import com.xjprojectc.base.dao.DataDaoImpl;
import com.xjprojectc.business.pojo.T_agentaccountinfo;
import com.xjprojectc.business.pojo.T_callpaymentrecord;
import com.xjprojectc.business.service.AgentaccountinfoService;
import com.xjprojectc.business.service.CallpaymentrecordService;
import com.xjprojectc.uitl.AppContext;
import com.xjprojectc.uitl.DateUtil;
import com.xjprojectc.uitl.JsonUtil;
import com.xjprojectc.uitl.Page;
import com.xjprojectc.webservice.Call;

/**
 * 
 * 
 * 充值列表管理
 * 
 * @author Administrator
 * 
 */

@SuppressWarnings("serial")
public class CallpaymentrecordAction extends SysBaseAction {
	private AgentaccountinfoService agentaccountinfoService;
	private CallpaymentrecordService callpaymentrecordService;
	private T_callpaymentrecord callpaymentrecord;
	private List<T_callpaymentrecord> callpaymentrecordList;
	private List<T_agentaccountinfo> agentaccountinfoList;
	private String errorMsg;
	private String code;
	private int parame;
	private String msg;
	private String id;

	private String count_num;
	private String count_money;
	private String count_yes_num;
	private String count_yes_money;
	private String count_no_num;
	private String count_no_money;
	private String count_refund_num;
	private String count_refund_money;

	private Map operators;

	private String isRenSend; // 是否重新发送信息

	/**
	 * 
	 * 列表页面数据处理
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String list() {
		if (callpaymentrecord == null) {
			callpaymentrecord = new T_callpaymentrecord();
		}
		T_agentaccountinfo user = this.getSysUser();

		operators = AppContext.NETWORK_OPERATORS;
		T_agentaccountinfo agent = new T_agentaccountinfo();
		agent.setField4(user.getUsername());
		agentaccountinfoList = agentaccountinfoService.getAgentaccountinfoByList(agent);
		agentaccountinfoList.add(user);

		if(user.getAgentlevel() == 1){
			if(callpaymentrecord.getAgentname() == null || "".equals(callpaymentrecord.getAgentname())){
				if(agentaccountinfoList != null && agentaccountinfoList.size() > 0){
					List<String> agentlist = new ArrayList<String>();
					for(T_agentaccountinfo age : agentaccountinfoList){
						agentlist.add("'"+age.getUsername()+"'");
					}
					callpaymentrecord.setAgentList(agentlist);
				}
			}
		}else{
			callpaymentrecord.setAgentname(user.getUsername());
		}
		
		List<T_callpaymentrecord> list = callpaymentrecordService.getCountDate(callpaymentrecord);
		if (list.size() > 0) {
			for (T_callpaymentrecord td : list) {
				if (td.getCount_type().equals("all")) {
					count_num = td.getCount_num();
					count_money = td.getCount_money();
				}
				if (td.getCount_type().equals("yes")) {
					count_yes_num = td.getCount_num();
					count_yes_money = td.getCount_money();
				}
				if (td.getCount_type().equals("no")) {
					count_no_num = td.getCount_num();
					count_no_money = td.getCount_money();
				}
				if (td.getCount_type().equals("refund")) {
					count_refund_num = td.getCount_num();
					count_refund_money = td.getCount_money();
				}
			}
		}
		count_num = count_num == null ? "0" : count_num;
		count_yes_num = count_yes_num == null ? "0" : count_yes_num;
		count_no_num = count_no_num == null ? "0" : count_no_num;
		count_refund_num = count_refund_num == null ? "0" : count_refund_num;
		count_money = count_money == null ? "0" : count_money;
		count_yes_money = count_yes_money == null ? "0" : count_yes_money;
		count_no_money = count_no_money == null ? "0" : count_no_money;
		count_refund_money = count_refund_money == null ? "0" : count_refund_money;

		
		
		

		int firstResult = (currentPage - 1) * pageSize;
		int maxResults = pageSize;
		Page page = new Page(callpaymentrecordService
				.getPageCount(callpaymentrecord));
		page.setCurrentPage(firstResult / maxResults + 1);
		super.setPageInfo(page);
		callpaymentrecord.setStart_row(page.getStartRow());
		callpaymentrecord.setEnd_row(page.getStartRow() + pageSize);

		String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		callpaymentrecordList = new ArrayList<T_callpaymentrecord>();

		List<T_callpaymentrecord> callList = callpaymentrecordService
				.getCallpaymentrecordByPager(callpaymentrecord);
		// 如果长时间没有充值成功 判断为退款
		if (callList != null && callList.size() > 0) {
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			for (T_callpaymentrecord call : callList) {
				if (call.getStatus().equals("0")
						&& DateUtil.timeDifference(time, call.getOccurtime(),"m") > 40
						&& call.getAgentname().equals(user.getUsername())) {
					call.setStatus("3");
				}
				callpaymentrecordList.add(call);
			}
		}
		return "list_view";
	}

	public String newData() {
		callpaymentrecord = new T_callpaymentrecord();
		callpaymentrecord.setStart_row(0);
		callpaymentrecord.setEnd_row(10);

		T_agentaccountinfo user = this.getSysUser();
		callpaymentrecord.setAgentname(user.getUsername());

		callpaymentrecordList = callpaymentrecordService
				.getCallpaymentrecordByPager(callpaymentrecord);
		JSONArray obj = new JSONArray();
		obj.addAll(callpaymentrecordList);
		try {
			this.jsonOut("{'success':'true','data':'" + obj.toString() + "'}");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	/**
	 * 
	 * 跳转到新增页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String toRecharge() {
		T_agentaccountinfo agent = agentaccountinfoService
				.getOneAgentaccountinfoByUsername(this.getSysUser()
						.getUsername());
		Double accountmoney = agent.getAccountmoney();
		code = accountmoney == null ? "0.00" : accountmoney.toString();
		return "recharge";
	}

	/**
	 * 增加
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String add() {
		String result = "{'success':'true','data':'充值成功'}";
		if (code != null) {
			T_agentaccountinfo user = this.getSysUser();
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(new Date());
			callpaymentrecord = (T_callpaymentrecord) JsonUtil
					.getObject4JsonString(code, T_callpaymentrecord.class);

			T_callpaymentrecord call = new T_callpaymentrecord();
			call.setPaymentmoney(callpaymentrecord.getPaymentmoney());
			call.setMobilephone(callpaymentrecord.getMobilephone());
			call.setStart_time(DateUtil.getNearTime(time, "h", -1));
			callpaymentrecordList = callpaymentrecordService.getCallpaymentrecordByList(call);
			if (callpaymentrecordList.size() > 0) {
				result= "{'success':'false','data':'同一号码同样的金额1个小时内无法进行重复缴费！'}";
			}else{ 
				call = new T_callpaymentrecord();
				call.setPaymentmoney(callpaymentrecord.getPaymentmoney());
				call.setMobilephone(callpaymentrecord.getMobilephone());
				call.setStatus("0");
				callpaymentrecordList = callpaymentrecordService.getCallpaymentrecordByList(call);
				if (callpaymentrecordList.size() > 0) {
					result =  "{'success':'false','data':'同一号码同样的金额在系统中已存在充值中，无法进行充值！'}";
				}else{
					callpaymentrecord.setOccurtime(time);
					callpaymentrecord.setSerialnumber(this.getLogid(user));
					callpaymentrecord.setStatus("0");
					callpaymentrecord.setAgentname(user.getUsername());
					callpaymentrecord.setAgentid(user.getField4());
					callpaymentrecord.setOperators(AppContext.NETWORK_OPERATORS.get(
									callpaymentrecord.getOperatorsnumber())
									.toString());
					callpaymentrecord.setAfterbalance(callpaymentrecord
							.getBeforebalance()
							+ callpaymentrecord.getPaymentmoney());
					callpaymentrecord.setSerialnumber(this.getLogid(user));
					callpaymentrecord.setAgentprofit(0f);
		
					JSONObject obj = new JSONObject();
					obj.put("user", Call.setCallUser(user));
					obj.put("data", JsonUtil.jsonStringDelEmpty(JSONObject
							.fromObject(callpaymentrecord).toString()));
					result = Call.getCall().exRecharge(obj.toString());
					obj = JSONObject.fromObject(result);
					if (obj.get("success").toString().equals("true")) {
						List<T_agentaccountinfo> userList = agentaccountinfoService
								.getAgentaccountinfoByList(Call.getClientUser(user));
						user = userList.get(0);
						if(user.getAgentlevel() == 2){
//							if(callpaymentrecord.getOperatorsnumber() == 1){
//								DataDaoImpl.updateAgentBalance("reduce", callpaymentrecord.getAgentprice(), user.getField4(), "");
//							}
							user.setAccountmoney(user.getAccountmoney()
									- callpaymentrecord.getAgentprice());
							agentaccountinfoService.updateAgentaccountinfo(user);
						}	
						callpaymentrecordService .addCallpaymentrecord(callpaymentrecord);
					}
				}
			}	
		}	
		try {
			this.jsonOut(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return NONE;
	}

	/**
	 * 充值退款
	 * 
	 * @return
	 */
	public String rechargeRefund() {
		T_agentaccountinfo user = this.getSysUser();
		callpaymentrecord = callpaymentrecordService
				.getOneCallpaymentrecord(id);
		JSONObject obj = new JSONObject();
		obj.put("user", Call.setCallUser(user));
		obj.put("data", callpaymentrecord.getSerialnumber());
		String result = Call.getCall().exRechargeRefund(obj.toString());
		obj = JSONObject.fromObject(result);
		if (obj.get("success").toString().equals("true")) {
			T_agentaccountinfo agent = agentaccountinfoService.getOneAgentaccountinfoByUsername(user.getUsername());
			//如果是二级代理商 并且是在线充值 需要给管理员退款
			if(agent.getAgentlevel() == 1){
				DataDaoImpl.updateAgentBalance("add", callpaymentrecord.getAgentprice(), agent.getUsername(), "");
			}else if(agent.getAgentlevel() == 2){
				if(callpaymentrecord.getOperatorsnumber() == 1){
					DataDaoImpl.updateAgentBalance("add", callpaymentrecord.getAgentprice(), agent.getField4(), "");
				}
				user = new T_agentaccountinfo();
				user.setUsername(agent.getUsername());
				user.setAccountmoney(agent.getAccountmoney()
						+ callpaymentrecord.getAgentprice());
				agentaccountinfoService.updateAgentaccountinfo(user);
				
			}
			
			T_callpaymentrecord call = new T_callpaymentrecord();
			call.setId(callpaymentrecord.getId());
			call.setStatus("2");
			callpaymentrecordService.updateCallpaymentrecord(call);

			try {
				this.jsonOut(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return NONE;
	}

	/**
	 * 
	 * 跳转到修改页面
	 * 
	 * @return
	 */
	public String toUpdate() {
		callpaymentrecord = callpaymentrecordService
				.getOneCallpaymentrecord(id);
		return "update_view";
	}

	/**
	 * 
	 * 修改
	 * 
	 * @return
	 */
	public String update() {
		callpaymentrecordService.updateCallpaymentrecord(callpaymentrecord);
		return "refresh";
	}

	/**
	 * 
	 * 删除
	 * 
	 * @return
	 */
	public String del() {
		callpaymentrecord = new T_callpaymentrecord();
		callpaymentrecord.setId(Integer.parseInt(id));
		callpaymentrecordService.delCallpaymentrecord(callpaymentrecord);
		return "refresh";
	}

	/**
	 * 
	 * 充值列表数据导出
	 * 
	 * @return
	 */
	public void export() {
		try {
			callpaymentrecordList = callpaymentrecordService
					.getCallpaymentrecordByList(callpaymentrecord);

			OutputStream os = getResponse().getOutputStream();// 取得输出流
			response.reset();// 清空输出流
			response.setHeader("Content-disposition",
					"attachment; filename=callpaymentrecordList.xls");// 设定输出文件头
			response.setContentType("application/msexcel");// 定义输出类型

			WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
			String tmptitle = "充值列表"; // 标题
			WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
			wsheet.setColumnView(0, 15);
			wsheet.setColumnView(1, 22);
			wsheet.setColumnView(2, 20);
			wsheet.setColumnView(3, 15);
			wsheet.setColumnView(4, 15);
			wsheet.setColumnView(5, 15);
			wsheet.setColumnView(6, 15);

			WritableFont wf = new WritableFont(WritableFont.ARIAL, 12,
					WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.CORAL);
			WritableCellFormat wcf = new WritableCellFormat(wf); // 单元格定义
			wcf.setBackground(Colour.BLUE); // 设置单元格的背景颜色
			wcf.setAlignment(Alignment.CENTRE); // 设置对齐方式

			WritableCellFormat center = new WritableCellFormat(wf); // 单元格定义
			center.setAlignment(Alignment.CENTRE); // 设置对齐方式

			NumberFormat doubleNunber = new NumberFormat("0.00");
			WritableCellFormat doubleFormate = new WritableCellFormat(
					doubleNunber);

			NumberFormat number = new NumberFormat("00000000000");
			WritableCellFormat nunberFormate = new WritableCellFormat(number);

			// 开始生成主体内容
			wsheet.addCell(new Label(0, 0, "代理商名菜", wcf));
			wsheet.addCell(new Label(1, 0, "充值时间", wcf));
			wsheet.addCell(new Label(2, 0, "充值号码", wcf));
			wsheet.addCell(new Label(3, 0, "上次余额", wcf));
			wsheet.addCell(new Label(4, 0, "充值金额", wcf));
			wsheet.addCell(new Label(5, 0, "充值状态", wcf));
			wsheet.addCell(new Label(6, 0, "本次余额", wcf));

			int num = 0;
			Double money = 0.00;
			int y_num = 0;
			Double y_money = 0.00;
			if (callpaymentrecordList != null
					&& callpaymentrecordList.size() > 0) {
				num = callpaymentrecordList.size();
				for (int i = 0; i < callpaymentrecordList.size(); i++) {
					callpaymentrecord = callpaymentrecordList.get(i);
					if (callpaymentrecord.getAgentname() != null) {
						wsheet.addCell(new Label(0, i + 1, callpaymentrecord
								.getAgentname()));
					}
					if (callpaymentrecord.getOccurtime() != null) {
						wsheet.addCell(new Label(1, i + 1, callpaymentrecord
								.getOccurtime()));
					}
					if (callpaymentrecord.getMobilephone() != null
							&& !"".equals(callpaymentrecord.getMobilephone())) {
						wsheet.addCell(new Number(2, i + 1,
								Double.parseDouble(callpaymentrecord
										.getMobilephone()), nunberFormate));
					}
					if (callpaymentrecord.getBeforebalance() != null
							&& !"".equals(callpaymentrecord.getBeforebalance())) {
						wsheet.addCell(new Number(3, i + 1, callpaymentrecord
								.getBeforebalance(), doubleFormate));
					}
					if (callpaymentrecord.getPaymentmoney() != null
							&& !"".equals(callpaymentrecord.getPaymentmoney())) {
						wsheet.addCell(new Number(4, i + 1, callpaymentrecord
								.getPaymentmoney(), doubleFormate));
					}
					wsheet.addCell(new Label(5, i + 1, callpaymentrecord
							.getStatus().equals("0") ? "充值中" : "成功"));
					if (callpaymentrecord.getAfterbalance() != null
							&& callpaymentrecord.getAfterbalance() != 0.0) {
						wsheet.addCell(new Number(6, i + 1, callpaymentrecord
								.getAfterbalance(), doubleFormate));
					}
					money += callpaymentrecord.getPaymentmoney();
					y_num += callpaymentrecord.getStatus().equals("0") ? 0 : 1;
					y_money += callpaymentrecord.getStatus().equals("0") ? 0
							: callpaymentrecord.getPaymentmoney();
				}
			}
			wsheet.mergeCells(0, num + 1, 6, num + 1);
			wsheet.addCell(new Label(0, num + 1, "共计充值: " + num + " 次,充值金额："
					+ money + " 元,成功充值: " + y_num + " 次,充值金额: " + y_money
					+ " 元,充值中: " + (num - y_num) + " 次,充值金额: "
					+ (money - y_money) + " 元", wcf));
			// 主体内容生成结束
			wbook.write(); // 写入文件
			wbook.close();
			os.close(); // 关闭流
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public CallpaymentrecordService getCallpaymentrecordService() {
		return callpaymentrecordService;
	}

	public void setCallpaymentrecordService(
			CallpaymentrecordService callpaymentrecordService) {
		this.callpaymentrecordService = callpaymentrecordService;
	}

	public T_callpaymentrecord getCallpaymentrecord() {
		return callpaymentrecord;
	}

	public void setCallpaymentrecord(T_callpaymentrecord callpaymentrecord) {
		this.callpaymentrecord = callpaymentrecord;
	}

	public List<T_callpaymentrecord> getCallpaymentrecordList() {
		return callpaymentrecordList;
	}

	public void setCallpaymentrecordList(
			List<T_callpaymentrecord> callpaymentrecordList) {
		this.callpaymentrecordList = callpaymentrecordList;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public int getParame() {
		return parame;
	}

	public void setParame(int parame) {
		this.parame = parame;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCount_num() {
		return count_num;
	}

	public void setCount_num(String count_num) {
		this.count_num = count_num;
	}

	public String getCount_money() {
		return count_money;
	}

	public void setCount_money(String count_money) {
		this.count_money = count_money;
	}

	public String getCount_yes_num() {
		return count_yes_num;
	}

	public void setCount_yes_num(String count_yes_num) {
		this.count_yes_num = count_yes_num;
	}

	public String getCount_yes_money() {
		return count_yes_money;
	}

	public void setCount_yes_money(String count_yes_money) {
		this.count_yes_money = count_yes_money;
	}

	public String getCount_no_num() {
		return count_no_num;
	}

	public void setCount_no_num(String count_no_num) {
		this.count_no_num = count_no_num;
	}

	public String getCount_no_money() {
		return count_no_money;
	}

	public void setCount_no_money(String count_no_money) {
		this.count_no_money = count_no_money;
	}

	public Map getOperators() {
		return operators;
	}

	public void setOperators(Map operators) {
		this.operators = operators;
	}

	public String getIsRenSend() {
		return isRenSend;
	}

	public void setIsRenSend(String isRenSend) {
		this.isRenSend = isRenSend;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public AgentaccountinfoService getAgentaccountinfoService() {
		return agentaccountinfoService;
	}

	public void setAgentaccountinfoService(
			AgentaccountinfoService agentaccountinfoService) {
		this.agentaccountinfoService = agentaccountinfoService;
	}

	public List<T_agentaccountinfo> getAgentaccountinfoList() {
		return agentaccountinfoList;
	}

	public void setAgentaccountinfoList(
			List<T_agentaccountinfo> agentaccountinfoList) {
		this.agentaccountinfoList = agentaccountinfoList;
	}

	public String getCount_refund_num() {
		return count_refund_num;
	}

	public void setCount_refund_num(String count_refund_num) {
		this.count_refund_num = count_refund_num;
	}

	public String getCount_refund_money() {
		return count_refund_money;
	}

	public void setCount_refund_money(String count_refund_money) {
		this.count_refund_money = count_refund_money;
	}

}
